package com.tanhua.server.interceptor;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {
//    拦截前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取请求头
        String token = request.getHeader("Authorization");

        //2、使用工具类，判断token是否有效
        boolean b = JwtUtils.verifyToken(token);
        //3、如果token失效，返回状态码401，拦截
        if (!b) {
            response.setStatus(401);
            return false;
        }
        //4、如果token正常可用，放行

        //解析token，获取id和手机号码，构造User对象，存入Threadlocal
        Integer id = (Integer) JwtUtils.getClaims(token).get("id");
        String mobile = (String) JwtUtils.getClaims(token).get("mobile");
        User user = new User();
        user.setId(Long.valueOf(id));
//        user.setId(106l);
        user.setMobile(mobile);
//        user.setMobile("13800138000");
        UserHolder.set(user);
        return true;

    }
}
